import pygame
import socket
import pickle
import random
import sys

# 全局定义
SCREEN_X = 600
SCREEN_Y = 600
WHITE = (255, 255, 255)
GREEN = (20, 220, 39)
RED = (136, 0, 21)
BLACK = (0, 0, 0)


# 蛇类
class Snake:
    def __init__(self):
        self.direction = pygame.K_RIGHT
        self.body = []
        for x in range(5):
            self.add_node()

    def add_node(self):
        left, top = (0, 0)  # 初始化在左上角
        if self.body:
            left, top = (self.body[0].left, self.body[0].top)
        node = pygame.Rect(left, top, 25, 25)
        if self.direction == pygame.K_LEFT:
            node.left -= 25
        elif self.direction == pygame.K_RIGHT:
            node.left += 25
        elif self.direction == pygame.K_UP:
            node.top -= 25
        elif self.direction == pygame.K_DOWN:
            node.top += 25
        self.body.insert(0, node)

    def del_node(self):
        self.body.pop()

    def is_dead(self):
        if self.body[0].x < 0 or self.body[0].x >= SCREEN_X:
            return True
        if self.body[0].y < 0 or self.body[0].y >= SCREEN_Y:
            return True
        if self.body[0] in self.body[1:]:
            return True
        return False

    def move(self):
        self.add_node()
        self.del_node()

    def change_direction(self, curkey):
        LR = [pygame.K_LEFT, pygame.K_RIGHT]
        UD = [pygame.K_UP, pygame.K_DOWN]
        if curkey in LR + UD:
            if (curkey in LR) and (self.direction in LR):
                return
            if (curkey in UD) and (self.direction in UD):
                return
            self.direction = curkey


# 食物类
class Food:
    def __init__(self):
        self.rect = pygame.Rect(-25, 0, 25, 25)

    def remove(self):
        self.rect.x = -25

    def set(self, snake_body):
        if self.rect.x == -25:
            while True:
                pos_x = random.randint(0, (SCREEN_X // 25) - 1) * 25
                pos_y = random.randint(0, (SCREEN_Y // 25) - 1) * 25
                self.rect.left = pos_x
                self.rect.top = pos_y
                if self.rect not in snake_body:
                    break


def show_text(screen, pos, text, color, font_size=60, font_bold=False, font_italic=False):
    cur_font = pygame.font.SysFont("宋体", font_size)
    cur_font.set_bold(font_bold)
    cur_font.set_italic(font_italic)
    text_fmt = cur_font.render(text, 1, color)
    screen.blit(text_fmt, pos)


def main():
    pygame.init()
    screen = pygame.display.set_mode((SCREEN_X, SCREEN_Y))
    pygame.display.set_caption('Snake Client')
    clock = pygame.time.Clock()

    def connect_to_server():
        conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        conn.connect(('127.0.0.1', 5555))
        return conn

    conn = connect_to_server()
    scores = 0
    is_dead = False
    high_score = 0
    new_record = False

    snake = Snake()
    food = Food()

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE and is_dead:
                    conn.close()
                    return main()  # 重新开始游戏并重新连接服务器
                snake.change_direction(event.key)

        if not is_dead:
            scores += 1
            snake.move()
        screen.fill(WHITE)
        for rect in snake.body:
            pygame.draw.rect(screen, GREEN, rect, 0)

        if snake.is_dead():
            is_dead = True
            conn.sendall(pickle.dumps(scores))
            received_high_score = pickle.loads(conn.recv(4096))
            if scores > received_high_score:
                new_record = True
                high_score = scores
            else:
                new_record = False
                high_score = received_high_score

            show_text(screen, (100, 200), 'YOU DEAD!', RED, 100)
            show_text(screen, (150, 260), f'Your score: {scores}', BLACK, 30)
            show_text(screen, (150, 300), f'Best score: {high_score}', BLACK, 30)
            show_text(screen, (150, 380), 'Press space to try again...', BLACK, 30)
        else:
            if food.rect.colliderect(snake.body[0]):
                scores += 50
                food.remove()
                snake.add_node()

            food.set(snake.body)
            pygame.draw.rect(screen, RED, food.rect, 0)

        show_text(screen, (50, 500), 'Scores: ' + str(scores), BLACK, 30)
        show_text(screen, (50, 540), 'High Score: ' + str(high_score), BLACK, 30)

        pygame.display.update()
        clock.tick(5)  # 减慢蛇的移动速度，每秒5帧


if __name__ == '__main__':
    main()
